package com.zbkj.crmeb.store.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.utils.PriceUtil;
import com.zbkj.crmeb.chant.model.ChannelActivity;
import com.zbkj.crmeb.chant.request.ActivityProductRequest;
import com.zbkj.crmeb.chant.request.BatchActivityRequest;
import com.zbkj.crmeb.chant.service.ChannelActivityService;
import com.zbkj.crmeb.merchant.admin.service.MerStoreProductService;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.dao.StoreProductActivityDao;
import com.zbkj.crmeb.store.response.StoreProductAttrValueResponse;
import com.zbkj.crmeb.store.response.StoreProductNormResponse;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 限时活动商品表 服务实现类
 * </p>
 *
 * @author wuzp
 * @since 2022-05-30
 */
@Service
public class StoreProductActivityServiceImpl extends ServiceImpl<StoreProductActivityDao, StoreProductActivity> implements StoreProductActivityService {

    @Resource
    private StoreProductActivityDao storeProductActivityDao;
    @Autowired
    private ChannelActivityService channelActivityService;
    @Autowired
    private MerStoreProductService storeProductService;
    @Autowired
    private StoreProductValueMerService storeProductValueMerService;
    @Autowired
    private StoreProductMerService storeProductMerService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private PriceUtil priceUtil;
    @Autowired
    private ChannelGroupBookingService channelGroupBookingService;
    @Autowired
    private StoreProductGroupActivityService storeProductGroupActivityService;


    @Override
    public CommonResult<Object> batchDelete(BatchActivityRequest request) {
        //在活动已开始之前可以添加/移除，在活动开始后不能移除商品
        ChannelActivity activity = channelActivityService.getById(request.getActivityId());
        if(activity == null || activity.getIsDel() == 1){
            throw new CrmebException("该活动不存在");
        }
        if(activity.getStartTime().before(new Date())){
            throw new CrmebException("该活动已开始");
        }
        return this.remove(Wrappers.<StoreProductActivity>lambdaQuery().eq(StoreProductActivity::getActivityId, request.getActivityId()).in(StoreProductActivity::getProductId, request.getIds())) ? CommonResult.success() : CommonResult.failed();
    }

    @Override
    public CommonResult<Object> batchAddActivity(BatchActivityRequest request, Integer merId) {
        List<Integer> ids = request.getIds();
        if(CollectionUtils.isEmpty(ids)){
            throw new CrmebException("商品id不能为空");
        }
        //加入活动：限时活动只包含未开始的活动
        ChannelActivity activity = channelActivityService.getById(request.getActivityId());
        if(activity == null || activity.getIsDel() == 1){
            throw new CrmebException("该活动不存在");
        }
        if(activity.getStartTime().before(new Date())){
            throw new CrmebException("该活动已开始");
        }
        //查询该商品是否加入其他活动（重合时间段类）
        activity.setIds(ids);
        List<StoreProductActivity> repeatList = storeProductActivityDao.getRepeatProductList(activity);
        if(CollectionUtils.isNotEmpty(repeatList)){
            throw new CrmebException("已有"+repeatList.size()+"条商品加入重合时间段活动，请重新选择");
        }
        //查询商品是否加入拼团活动
        List<Integer> groupActivityIds = channelGroupBookingService.getInProgressActivityIds(merId);
        List<StoreProductGroupActivity> groupActivities = storeProductGroupActivityService.getByActivityIds(groupActivityIds);
        if (CollectionUtils.isNotEmpty(groupActivities)){
            //加入拼团的商品id
            List<Integer> groupActivityProductIds = groupActivities.stream().map(StoreProductGroupActivity::getProductId).collect(Collectors.toList());
            int count = 0;
            for (Integer id : ids){
                if (groupActivityProductIds.contains(id)){
                    count ++;
                }
            }
            if (count > 0){
                throw new CrmebException("已有"+ count +"条商品加入拼团活动，请重新选择");
            }
        }

        //排除已加入
        List<StoreProductActivity> activityList = this.list(Wrappers.<StoreProductActivity>lambdaQuery().eq(StoreProductActivity::getActivityId, request.getActivityId()).in(StoreProductActivity::getProductId, ids));
        List<Integer> list = activityList.stream().map(StoreProductActivity::getProductId).collect(Collectors.toList());
        ids.removeAll(list);
        if(CollectionUtils.isNotEmpty(ids)){
            List<StoreProductAttrValue> attrValueList = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().in(StoreProductAttrValue::getProductId, ids));
            List<StoreProductActivity> productActivityList = new ArrayList<>();
            for (StoreProductAttrValue value : attrValueList) {
                StoreProductActivity storeProductActivity = new StoreProductActivity();
                storeProductActivity.setProductId(value.getProductId());
                storeProductActivity.setSourceSkuId(value.getSourceSkuId());
                storeProductActivity.setActivityId(request.getActivityId());
                productActivityList.add(storeProductActivity);
            }
            return this.saveBatch(productActivityList) ? CommonResult.success() : CommonResult.failed();
        }
        return CommonResult.success() ;
    }

    @Override
    public StoreProductResponse getByProductId(Integer id, Integer activityId,Integer merId) {
        StoreProductResponse storeProductResponse = new StoreProductResponse();
        //判断该商品自建还是云仓
        StoreProduct storeProduct = storeProductService.getById(id);
        if(!Objects.equals(storeProduct.getMerId(), merId)){
            StoreProductNormResponse normResponse = storeProductService.getSupplierByProductId(id, merId);
            List<StoreProductResponse> products = normResponse.getProducts();
            Map<Integer, StoreProductResponse> map = products.stream().collect(Collectors.toMap(StoreProductResponse::getId, e -> e));
            StoreProductResponse response = map.get(id);
            if(response != null){
                storeProductResponse = response;
            }
        }else {
            storeProductResponse = storeProductService.getByProductId(id, merId, false,false, null, false);
        }
        List<StoreProductAttrValueResponse> responseAttrValue = storeProductResponse.getAttrValue();
        if(CollectionUtils.isNotEmpty(responseAttrValue)){
            List<StoreProductAttrValue> valueList = new ArrayList<>();
            for (StoreProductAttrValueResponse valueResponse : responseAttrValue) {
                StoreProductAttrValue value = new StoreProductAttrValue();
                BeanUtils.copyProperties(valueResponse,value);
                valueList.add(value);
            }
            priceUtil.calcSpikePrice(valueList,activityId,merId);
            Map<String, StoreProductAttrValue> valueMap = valueList.stream().collect(Collectors.toMap(StoreProductAttrValue::getSourceSkuId, e -> e));
            for (StoreProductAttrValueResponse valueResponse : responseAttrValue) {
                valueResponse.setSpikePrice(valueMap.get(valueResponse.getSourceSkuId()).getSpikePrice());
            }
        }
        StoreProductActivity activity = this.getOne(Wrappers.<StoreProductActivity>lambdaQuery().eq(StoreProductActivity::getActivityId, activityId)
                .eq(StoreProductActivity::getProductId, id).last("LIMIT 1"));
        if(activity != null){
            storeProductResponse.setSort(activity.getSort());
        }
        return storeProductResponse;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateActivityProduct(ActivityProductRequest request, Integer merId) {
        List<StoreProductActivity> activityList = this.list(Wrappers.<StoreProductActivity>lambdaQuery().eq(StoreProductActivity::getActivityId, request.getActivityId())
                .eq(StoreProductActivity::getProductId, request.getProductId()));
        if(CollectionUtils.isEmpty(activityList)){
            throw new CrmebException("该活动商品不存在");
        }
        Map<String, StoreProductActivity> activityMap = activityList.stream().collect(Collectors.toMap(StoreProductActivity::getSourceSkuId, e -> e));
        List<StoreProductValueMer> storeProductValueMerList = request.getStoreProductValueMerList();
        if(request.getIsModify() || request.getIsSpike()){
            List<StoreProductValueMer> productValueMerList = new ArrayList<>();
            List<StoreProductActivity> storeProductActivityList = new ArrayList<>();
            for (StoreProductValueMer storeProductValueMer : storeProductValueMerList) {
                StoreProductValueMer productValueMer = Optional.ofNullable(storeProductValueMerService.getOne(
                        Wrappers.lambdaQuery(StoreProductValueMer.class)
                                .eq(StoreProductValueMer::getProductId, request.getProductId())
                                .eq(StoreProductValueMer::getSourceSkuId, storeProductValueMer.getSourceSkuId())
                                .orderByDesc(StoreProductValueMer::getUpdateTime)
                                .last("LIMIT 1")))
                        .orElse(new StoreProductValueMer());
                if(request.getIsModify()){
                    if(storeProductValueMer.getPrice() == null){
                        throw new CrmebException("商品sku售价:" + storeProductValueMer.getPrice() + "不能为空" );
                    }
                    if(BigDecimal.ZERO.compareTo(storeProductValueMer.getPrice()) > 0){
                        throw new CrmebException("商品sku售价:" + storeProductValueMer.getPrice() + "不能低于0元" );
                    }
                    productValueMer.setPrice(storeProductValueMer.getPrice());
                }
                if(request.getIsSpike()){
                    StoreProductActivity productActivity = activityMap.get(storeProductValueMer.getSourceSkuId());
                    if(productActivity == null){
                        productActivity = new StoreProductActivity();
                        productActivity.setActivityId(request.getActivityId());
                        productActivity.setProductId(request.getProductId());
                        productActivity.setSourceSkuId(storeProductValueMer.getSourceSkuId());
                        productActivity.setSort(activityList.get(0).getSort());
                    }

                    if(storeProductValueMer.getPrice() == null){
                        throw new CrmebException("商品sku秒杀价:" + storeProductValueMer.getPrice() + "不能为空" );
                    }
                    if(BigDecimal.ZERO.compareTo(storeProductValueMer.getPrice()) > 0){
                        throw new CrmebException("商品sku秒杀价:" + storeProductValueMer.getPrice() + "不能低于0元" );
                    }
                    productActivity.setSpikePrice(storeProductValueMer.getSpikePrice());
                    storeProductActivityList.add(productActivity);
                }
                productValueMer.setProductId(storeProductValueMer.getProductId())
                        .setSourceSkuId(storeProductValueMer.getSourceSkuId());
                productValueMerList.add(productValueMer);
            }
            storeProductValueMerService.saveOrUpdateBatch(productValueMerList);
            this.saveOrUpdateBatch(storeProductActivityList);
        }
        if(request.getIsModify()){
            StoreProductMer storeProductMer = storeProductMerService.getOne(Wrappers.<StoreProductMer>lambdaQuery()
                    .eq(StoreProductMer :: getProductId, request.getProductId())
                    .last("LIMIT 1"));
            storeProductMer = null == storeProductMer ? new StoreProductMer() : storeProductMer;
            storeProductMer.setProductId(request.getProductId());
            //查询sku实时库存,获取最低价格
            List<StoreProductAttrValue> storeProductAttrValueList = storeProductAttrValueService.list(Wrappers.lambdaQuery(StoreProductAttrValue.class).eq(StoreProductAttrValue::getProductId, request.getProductId()).gt(StoreProductAttrValue::getStock, 0));
            List<String> list = storeProductAttrValueList.stream().map(StoreProductAttrValue::getSourceSkuId).collect(Collectors.toList());
            BigDecimal minPrice;
            if(CollectionUtils.isNotEmpty(list)){
                minPrice = request.getStoreProductValueMerList().stream().filter(e->list.contains(e.getSourceSkuId())).map(StoreProductValueMer::getPrice).filter(Objects::nonNull).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
            }else {
                minPrice = request.getStoreProductValueMerList().stream().map(StoreProductValueMer::getPrice).filter(Objects::nonNull).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
            }
            storeProductMer.setPrice(minPrice);
            storeProductMer.setPriceType(1);
            storeProductMerService.saveOrUpdate(storeProductMer);
        }
        //修改排序
        if(!Objects.equals(request.getSort(),activityList.get(0).getSort())){
            this.update(Wrappers.<StoreProductActivity>lambdaUpdate()
                    .eq(StoreProductActivity::getActivityId,request.getActivityId())
                    .eq(StoreProductActivity::getProductId,request.getProductId())
                    .set(StoreProductActivity::getSort,request.getSort()));
        }
        return true;
    }

}
